package com.linkdood.app.web.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.linkdood.app.constants.ErrorCode;
import com.linkdood.app.exception.GeneralException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 获取客户服务中心访问地址
 *
 * @author chenfayong
 */
@Slf4j
@RestController
@RequestMapping("/api/customer-service")
public class CustomerServiceResource {

    public static final Logger logger = LoggerFactory.getLogger(CustomerServiceResource.class);

    @Value("${vrv.customer-service.elogo}")
    private String customerServiceElogo;

    @Value("${vrv.customer-service.url}")
    private String customerServiceUrl;

    @GetMapping("/address")
    public ResponseEntity<String> address() {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        try {
            String uuid = UUID.randomUUID().toString();
            String keyToken = getKeyToken(httpClient, uuid);
            String authToken = getAuthToken(httpClient, uuid, keyToken);
            String address = getChatAddress(httpClient, uuid, authToken);
            return ResponseEntity.ok(address);
        } catch (Exception e) {
            logger.error("get customer service address error.", e);
            throw new GeneralException(ErrorCode.ERROR_UNKNOWN_THIRD_PARTY_PLATFORM);
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch(IOException ioe) {
                logger.error("unknown input or output exception.", ioe);
            }
        }
    }

    private String getKeyToken(CloseableHttpClient httpClient, String uuid) throws Exception {
        StringBuilder params = new StringBuilder("type=key");
        params.append("&uuid=");
        params.append(uuid);

        HttpGet httpGet = new HttpGet(customerServiceUrl + "?" + params);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        String res = EntityUtils.toString(httpResponse.getEntity());
        httpResponse.close();

        JSONObject resJson = JSON.parseObject(res);
        Integer code = resJson.getInteger("code");
        if (!code.equals(200)) {
            throw new IllegalAccessException("illegal access exception");
        }
        httpResponse.close();
        return resJson.getString("token");
    }

    private String getAuthToken(CloseableHttpClient httpClient, String uuid, String keyToken) throws Exception {
        HttpPost httpPost = new HttpPost(customerServiceUrl);
        List<NameValuePair> entityList = new ArrayList<>();
        BasicNameValuePair nameValuePair = new BasicNameValuePair("pstr", DigestUtils.sha256Hex(customerServiceElogo));
        entityList.add(nameValuePair);
        nameValuePair = new BasicNameValuePair("type", "auth");
        entityList.add(nameValuePair);
        nameValuePair = new BasicNameValuePair("token", keyToken);
        entityList.add(nameValuePair);
        nameValuePair = new BasicNameValuePair("uuid", uuid);
        entityList.add(nameValuePair);

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(entityList);
        httpPost.setEntity(formEntity);
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        String res = EntityUtils.toString(httpResponse.getEntity());
        httpResponse.close();

        JSONObject resJson = JSON.parseObject(res);
        Integer code = resJson.getInteger("code");
        if (!code.equals(200)) {
            throw new IllegalAccessException("illegal access exception");
        }
        httpResponse.close();
        return resJson.getString("token");
    }

    private String getChatAddress(CloseableHttpClient httpClient, String uuid, String authToken) throws Exception {
        StringBuilder params = new StringBuilder("type=chat");
        params.append("&uuid=");
        params.append(uuid);
        params.append("&token=");
        params.append(authToken);

        HttpGet httpGet = new HttpGet(customerServiceUrl + "?" + params);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        String res = EntityUtils.toString(httpResponse.getEntity());
        httpResponse.close();

        JSONObject resJson = JSON.parseObject(res);
        Integer code = resJson.getInteger("code");
        if (!code.equals(200)) {
            throw new IllegalAccessException("illegal access exception");
        }
        String url = resJson.getString("url");
        String token = resJson.getString("token");
        return url +"&token=" +token;
    }
}
